package com.novice.config;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> headers = request.getHeaders();
        // 2 获取请求头中的token
        String token = headers.getFirst("Token");
        if(token == null || "".equals(token)){
            // a. token为空
            // b. token不为空，但token不正确
            System.out.println("token为空");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else {
            // token不为空，放行
            System.out.println("token不为空");
            return chain.filter(exchange);
        }
    }
}
